<template>
  <div class="mt20">
    <el-tabs type="border-card">
      <el-tab-pane label="手游">
        <el-card class="box-card mt20" :body-style="{ padding: '18px 0px 5px', boxSizing: 'border-box' }">
          <el-row class="title">
            <el-col :lg="2" class="tac module-title ml20">
              <el-select v-model="queryServerInfo.id" @change="searchWyServer(1)" filterable>
                <el-option v-for="(item, index) in gameOptions" :key="index" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-col>
            <el-col :lg="5" class="tac module-title ml20">
              <el-date-picker
                v-model="queryTime"
                @change="searchWyServer"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-col>

            <el-col :lg="3" class="tal module-title ml20">
              <el-button plain type="primary" @click="reset">重置</el-button>
            </el-col>
            <el-col :lg="8" class="tar module-title">
              <el-button plain type="primary" @click="addServerMerge">添加合服</el-button>
              <el-button plain type="primary" @click="downloadExcel(false)" :loading="downloadLoading1">导出当前页</el-button>
              <el-button plain type="primary" @click="downloadExcel(true)" :loading="downloadLoading2">导出所有页</el-button>
            </el-col>
          </el-row>
          <el-table :data="tableData" :height="tableHeight" v-loading="tableLoading">
            <el-table-column label="序号" type="index"> </el-table-column>
            <el-table-column prop="game_name" label="游戏名称"> </el-table-column>
            <el-table-column prop="recently" label="最近合服区号">
              <template slot-scope="scope">
                <pre v-html="scope.row.recently"></pre>
              </template>
            </el-table-column>
            <el-table-column prop="combined_time" label="最近合服时间">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.combined_time | formatTime }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="presentMain" label="目前主区服"> </el-table-column>
            <el-table-column prop="detailServer" label="详细区服">
              <template slot-scope="scope">
                <pre v-html="scope.row.detailServer"></pre>
              </template>
            </el-table-column>
            <el-table-column prop="op" label="操作">
              <template slot-scope="scope">
                <el-button @click="deleteServer(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="tac"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="pagination.currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pagination.perPages"
            layout="sizes, prev, pager, next"
            :total="pagination.total"
          >
          </el-pagination>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="页游"></el-tab-pane>
    </el-tabs>
    <!-- 合服计划 -->
    <el-dialog
      :modal-append-to-body="false"
      :top="userAgent ? '60px' : '6vh'"
      :title="'添加合服'"
      :visible.sync="serverMergeFlag"
      width="1200px"
      @close="closeDialog"
    >
      <div class="wid-100 pt20 pb20">
        <el-form class="wid-100" inline label-position="right" label-width="140px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="游戏：">
                <el-select v-model="newServerMerge.game_id" filterable style="width: 240px" @change="getServer">
                  <el-option v-for="(item, index) in gameOptions2" :key="index" :label="item.label" :value="item.value"> </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="合服时间：">
                <el-date-picker v-model="newServerMerge.combined_time" type="datetime" placeholder="选择日期时间"> </el-date-picker>
              </el-form-item>
              <el-form-item label=" ">
                <el-upload
                  class="upload-demo ml10 mr10"
                  action="invalid"
                  :limit="1"
                  style="width: 120px; display: inline"
                  :http-request="uploadFile"
                  :show-file-list="false"
                  :file-list="fileList"
                >
                  <el-button plain type="primary">批量上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24" :offset="0" v-for="(item, index) in newServerMerge.master_slave_list" :key="index">
              <el-form-item :label="'主服' + (index + 1) + '：'">
                <el-select v-model="newServerMerge.master_slave_list[index].master_serial_num" filterable style="width: 240px">
                  <el-option v-for="o in serverOptions" :key="o.value" :label="o.label" :value="o.value"> </el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="'次服' + (index + 1) + '：'">
                <el-select v-model="newServerMerge.master_slave_list[index].slave_server_num_list" multiple filterable style="width: 240px">
                  <el-option v-for="o in serverOptions" :key="o.value" :label="o.label" :value="o.value"> </el-option>
                </el-select>
              </el-form-item>
              <el-button type="primary" @click="addMergeServer" v-if="index == 0">添加</el-button>
              <el-button @click.prevent="removeMergeServer(item)" v-if="index > 0">删除</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="passCancel">取 消</el-button>
        <el-button type="primary" @click="passConfirm" size="small" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// 复制
export default {
  data() {
    return {
      flag: false,
      btnLoading: false,
      downloadLoading1: false,
      downloadLoading2: false,
      gameOptions: [{ value: '', label: '所有游戏(all)' }], // 所有游戏
      gameOptions2: [], // 游戏列表去掉所有游戏
      serverOptions: [], // 区服列表
      tableData: [], // 数据
      serverMergeFlag: false, // 编辑/添加 弹窗
      // 分页
      pagination: {
        total: 0, // 表格数据条数
        pages: 0, // 总页数
        perPages: 10, // 每页的数量
        currentPage: 1, // 当前页
      },
      // 查询
      queryServerInfo: {
        id: '', // 游戏id
        page: 1, // 第一页默认第一(非必填)
        per_page: 10, // 每页数量默认10(非必填)
      },
      // 上传
      fileList: [],
      // 新建 添加服务器字段
      newServerMerge: {
        master_slave_list: [{}],
      },
      // 分类
      total_category: [],
      queryTime: [],
      tableLoading: false,
    };
  },
  computed: {},
  created() {
    this.getServerListState();
    this.getCurrentScreen();
  },
  mounted() {},
  methods: {
    deleteServer(r) {
      let id = r.id;
      this.$confirm('此操作将删除该服务器合并计划, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$api.deleteServerMerge({ id: id }).then(res => {
          if (res.code == 200 || res.code == 0) {
            this.$message.success('删除成功');
            this.getServerListState();
          }
        });
      });
    },
    addMergeServer() {
      this.newServerMerge.master_slave_list.push({});
    },
    removeMergeServer(item) {
      var index = this.newServerMerge.master_slave_list.indexOf(item);
      if (index !== -1) {
        this.newServerMerge.master_slave_list.splice(index, 1);
      }
    },
    // 查询
    searchWyServer(num = 0) {
      this.queryServerInfo.page = 1;
      this.queryServerInfo.combined_time__gte = this.queryTime[0] ? this.toDate(this.queryTime[0]) : '';
      this.queryServerInfo.combined_time__lte = this.queryTime[1] ? this.toDate(this.queryTime[1]) : '';
      this.getServerListState(this.queryServerInfo);
    },
    // 每页数量变化
    handleSizeChange(val) {
      this.queryServerInfo.per_page = val;
      this.getServerListState(this.queryServerInfo);
    },
    // 当前页
    handleCurrentChange(val) {
      this.queryServerInfo.page = val;
      this.getServerListState(this.queryServerInfo);
    },
    // 获取游戏列表信息
    getServerListState(params) {
      return new Promise(resolve => {
        this.tableLoading = true;
        this.getWyGameList().then(gameData => {
          let queryObj = params || this.queryServerInfo;
          let queryflag = !!params;
          this.$api.gameServerMergeList(queryObj).then(res => {
            this.tableLoading = false;
            if (res.code == 0 || res.code == 200) {
              // 处理表格显示数据
              this.tableData = res.items;
              this.tableData.map(single => {
                let o = gameData.find(item => {
                  return item.id == single.game_id;
                });
                single.game_name = o ? o.name : '无效游戏id';
              });
              this.modifFnc();
              if (queryflag) {
                this.$message.success('查询成功');
              }
              // 分页
              this.pagination.currentPage = res.page;
              this.pagination.pages = res.pages;
              this.pagination.total = res.total;
              this.pagination.perPages = res.per_page;
              resolve(res.items);
            }
          });
        });
      });
    },
    modifFnc() {
      this.tableData.map(item => {
        let str = '';
        Object.entries(item.master_slave_hstore).forEach(subItem => {
          let num = `${subItem[0].split(',').length + subItem[1].split(',').length}`;
          let big = this.turnBig(num);
          str += `${subItem[0]}、${subItem[1]} ${big}合一，` + '\n';
        });
        item.recently = str.replace(/\,/g, '、');
        item.presentMain = Object.keys(item.master_slave_server).join('，');
        let str2 = '';
        Object.entries(item.master_slave_server).forEach(subItem => {
          str2 += `${subItem[0]}/${subItem[1]}，` + '\n';
        });
        item.detailServer = str2.replace(/\,/g, '/');
      });
    },
    // 阿拉伯转中文
    turnBig(num) {
      var N = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
      function convertToChinese(num) {
        var str = num.toString();
        var len = num.toString().length;
        var C_Num = [];
        for (var i = 0; i < len; i++) {
          C_Num.push(N[str.charAt(i)]);
        }
        return C_Num.join('');
      }

      var chinese = convertToChinese(num);

      return chinese;
    },
    // 获取游戏列表下拉框信息
    getWyGameList() {
      return new Promise((resolve, reject) => {
        // 1、获取游戏名+ 简称
        this.$api.getWyGameSelectList().then(res => {
          if (res.code == 0 || res.code == 200) {
            let list = res.data.map((item, index) => {
              return {
                value: item.id,
                label: `${item.name} - ${item.interface_name}`,
              };
            });
            this.gameOptions = [...this.gameOptions, ...list];
            this.gameOptions2 = [...list];
            resolve(res.data);
          }
        });
      });
    },
    getServer(v) {
      this.$api.checkGameServerList({ game_id: v }).then(res => {
        if (res.code == 0 || res.code == 200) {
          this.serverOptions = [...res.data];
          this.serverOptions.map(item => {
            item.value = item.serial_num;
            item.label = item.master_serial_num ? `${item.server_name}服 - 已合入${item.master_serial_num}服` : `${item.server_name}服`;
          });
        }
      });
    },
    // 新建 / 编辑 通过
    passConfirm() {
      this.newServerMerge.combined_time = this.toDateTime(this.newServerMerge.combined_time);
      // 1、检查该输入的都输入了没
      if (this.checkInputInfo()) return;
      this.btnLoading = true;
      this.$api.newServerMerge(this.newServerMerge).then(res => {
        this.btnLoading = false;
        if (res.code == 200 || res.code == 0) {
          this.$message.success('新建合服成功！');
          this.serverMergeFlag = false;
          this.newServerMerge = {
            master_slave_list: [{}],
          };
          this.getServerListState();
        }
      });
    },
    passCancel() {
      this.serverMergeFlag = false;
    },
    // 检查输入的内容有没有完整
    checkInputInfo() {
      if (!this.newServerMerge.game_id) {
        this.$message.warning('请选择游戏名称');
        return true;
      }
      if (!this.newServerMerge.combined_time) {
        this.$message.warning('请选择合服时间');
        return true;
      }
      if (!this.newServerMerge.master_slave_list[0].master_serial_num) {
        this.$message.warning('请输入主服名称');
        return true;
      }
      if (this.newServerMerge.master_slave_list[0].slave_server_num_list.length == 0) {
        this.$message.warning('请输入次服名称');
        return true;
      }
      return false;
    },
    // 添加服务器
    addServerMerge() {
      this.serverMergeFlag = true;
    },
    // 自定义上传事件
    uploadFile(e) {
      let formFile = new FormData();
      let imgName = 'file';
      formFile.append(imgName, e.file);
      this.$api
        .importServerMerge(formFile)
        .then(res => {
          if (res.code == 0 || res.code == 200) {
            this.$message.success('上传成功');
            this.serverMergeFlag = false;
            this.fileList = [];
            this.newServerMerge = {
              master_slave_list: [{}],
            };
            this.getServerListState();
          }
        })
        .catch(err => {});
    },
    // 重置
    reset() {
      this.queryTime = [];
      this.queryServerInfo.id = '';
      this.queryServerInfo.combined_time__gte = '';
      this.queryServerInfo.combined_time__lte = '';
      this.queryServerInfo.page = 1;
      this.queryServerInfo.per_page = 10;
      this.pagination.currentPage = 1;
      this.pagination.perPages = 10;
      this.getServerListState(this.queryServerInfo);
    },
    closeDialog() {},
    // 下载excel
    async downloadExcel(flage) {
      let excel = '<table>';
      //设置表头
      let list;
      if (!flage) {
        // 当前页
        this.downloadLoading1 = true;
        list = this.tableData;
      } else {
        // 所有页
        this.downloadLoading2 = true;
        this.queryServerInfo.page = 1;
        this.queryServerInfo.per_page = 9999;
        list = await this.getServerListState(this.queryServerInfo);
      }
      let row =
        '<tr>' +
        '<td>序号</td>' +
        '<td>游戏名称</td>' +
        '<td>最近合服区号</td>' +
        '<td>最近合服时间</td>' +
        '<td>目前主区服</td>' +
        '<td>详细区服</td>' +
        '</tr>';
      //换行
      excel += row;
      let l = list.map((o, i) => {
        return `
        <tr>
          <td>${i + 1}</td>
          <td>${o.game_name}</td>
          <td>${o.recently}</td>
          <td>${o.combined_time}</td>
          <td>${o.presentMain}</td>
          <td>${o.detailServer}</td>
        </tr>`;
      });

      excel += l.join('');
      excel += '</table>';
      //利用时间起文件名称
      var date = new Date();
      var fileName = '服务器合并' + date.getFullYear() + (date.getMonth() + 1) + date.getDate() + '号' + date.getHours() + '点' + date.getMinutes() + '分';
      this.tableToExcel(excel, fileName);
      this.downloadLoading1 = false;
      this.downloadLoading2 = false;
      this.reset();
    },
  },
  components: {},
};
</script>
<style lang='stylus' scoped>
body {
}

.el-dialog__body {
  padding: 10px 20px 30px !important;
}

.el-table .cell {
  white-space: pre-line;
}
</style>
